package com.xiyuan.smartutils.client.http;

import com.xiyuan.smartutils.StrUtils;
import com.xiyuan.smartutils.Validates;

import java.io.IOException;
import java.net.HttpURLConnection;

/**
 * HTTP/HTTPS PUT请求
 * 1.和POST不同的时PUT以流为主，传入bytes
 * 2.和POST不同的是mimeType和encoding可以为null则不传入
 *
 * @version v1.0.0 @author lgz 2017-9-21 新建与整理
 */
public class HttpPut extends HttpClient {
    private byte[] bytes;
    private String mimeType;
    private String encoding;
    
    public HttpPut(String url) {
        super(url, _PUT_);
    }
    
    public void setContentType(String mimeType, String encoding) {
        this.mimeType = StrUtils.trim(mimeType);
        this.encoding = StrUtils.trim(encoding);
    }
    
    public HttpPut setEncoding(String encoding) {
        if (encoding != null) {
            this.encoding = encoding;
        }
        
        return this;
    }
    
    public HttpPut setBytes(byte[] bytes) {
        this.bytes = bytes;
        return this;
    }
    
    @Override
    protected boolean doPreRequestProperty() {
        if (bytes == null || bytes.length == 0) {
            return true;
        }
        
        setDoOutput(true);
        if (hasRequestHeader(_CONTENT_TYPE_) && Validates.isNotEmpty(mimeType)) {
            // 有可能在执行前已设置属性
            if (Validates.isEmpty(encoding)) {
                addRequestProperty(_CONTENT_TYPE_, mimeType);
            }
            else {
                addRequestProperty(_CONTENT_TYPE_, mimeType + "; charset=" + encoding);
            }
        }
        
        addRequestProperty(_CONTENT_LENGTH_, bytes.length);
        return true;
    }
    
    @Override
    protected void doWriteContent(HttpURLConnection conn) throws IOException {
        if (bytes == null || bytes.length == 0) {
            return;
        }
        
        conn.getOutputStream().write(bytes);
    }
}
